package functions.ems_accountant_job_pool;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import com.beans.GroupBasicBean;
import com.beans.GroupCrewBean;
import com.beans.ORGBean;
import com.crc.mam.BaseCase;
import coms.AutoException;
import coms.Constants;
import coms.TestDateString;
import frame.HttpHelper;
import functions.mams_rest.Org;
import functions.mams_rest.Sys;

public class Group extends BaseCase{
  
  private org.slf4j.Logger logger = LoggerFactory.getLogger(Group.class);
  String groupName;
  ORGBean selectedOrg;
  
  public ORGBean getSelectedOrg() {
    return selectedOrg;
  }


  public void setSelectedOrg(ORGBean selectedOrg) {
    this.selectedOrg = selectedOrg;
  }


  public String getGroupName() {
    return groupName;
  }


  public void setGroupName(String groupName) {
    this.groupName = groupName;
  }


  /**
   * 创建工作组
   * @param groupType
   * @param delFlg
   * @param companyName
   * @param deptName
   * @param membersTasks
   * @return 返回工作组名称，key = firstAuditGroupName，secondAuditGroupName，groupOrg,companyName,status
   */
  public void save2update(int groupType,String delFlg,String companyName,String deptName,String membersTasks) {
    /**
     * 调用值集接口得到小组类型和key值
     */
    Sys sys = new Sys();
    JSONArray keys = sys.getValue("ACCOUNT_GROUP_TYPE");
    String value = "";
    for(int i =0;i<keys.length();i++) {
      JSONObject object = (JSONObject) keys.get(i);
      if(object.getString("vsiKey").equals(String.valueOf(groupType))) {
        value = object.getString("vsiValue");
        break;
      }
    }
      groupName = TestDateString.getDateString()+value;
       
    Org org = new Org();
    ORGBean deptOrg = org.getHasEmployeesOrg(companyName, deptName);
    ArrayList<ORGBean> users = org.getDeptUsers(deptOrg);
    if(users == null) {
      status = false;
      remark = companyName+ " 公司无人员，终止测试";
      logger.error("该公司无人员，终止测试");
      throw new AutoException("该公司无人员，终止测试");
    }

    selectedOrg = deptOrg;
   
    ORGBean leaderBean = users.get(0);
    String groupLeaderId = leaderBean.getId();
    String groupLeaderName = leaderBean.getTitle();
    String crewNames = "";
    String groupMembers = "";
    String crewCodes = "";

    for(int i=0;i<users.size();i++) {
      ORGBean user = users.get(i);
      if(groupMembers.equals("")) {
        groupMembers = groupMembers + user.getId();
      }else {
        groupMembers =groupMembers + ","+ user.getId();
      }
      if(crewNames.equals("")) {
        crewNames = crewNames + user.getTitle();
      }else {
        crewNames =crewNames + ","+ user.getTitle();
      }
      if(crewCodes.equals("")) {
        crewCodes = crewCodes + user.getCode();
      }else {
        crewCodes =crewCodes + ","+ user.getCode();
      }
    }
    String params = "{\"groupName\":\""+groupName+"\",\"groupType\":\""+groupType+"\","
        + "\"delFlg\":\""+delFlg +"\",\"groupLeaderIdStr\":\""+groupLeaderId+"\","
            + "\"groupLeaderName\":\""+groupLeaderName+"\",\"memberTasks\":"+membersTasks+","
                + "\"groupMembers\":\""+groupMembers+"\",\"groupDeptName\":\""+deptOrg.getTitle()+"\","
                    + "\"groupDeptId\":\""+deptOrg.getId()+"\",\"crewNames\":\""+crewNames+"\","
                        + "\"crewCodes\":\""+crewCodes+"\"}";
    
    logger.info("save group param : " + params);
    String url = Constants.SAVE_2_UPDATE_URL;
    try {
      result = HttpHelper.post(params, url);
      logger.info("save2update --- " + result);
      status = HttpHelper.isOk;
      if (status) {
       
      }else {
        status = false;
        remark = "保存会计任务小组失败";
        throw new AutoException("保存会计任务小组失败");
      }
    }catch(Exception e) {
      status = false;
      remark = e.getStackTrace().toString();
      throw new AutoException("保存会计任务小组失败");
    }
  
        
  }
  
  /**
   * 根据小组类型，下拉列表框搜索出对应的小组
   * @param groupType,groupName
   * @return
   */
  public GroupBasicBean findByNameOrType(String groupType,String groupName) {
    GroupBasicBean groupBasicBean = null;
    String url =Constants.FIND_BY_NAME_OR_TYPE_URL + "groupType="+groupType;
    try {
      result = HttpHelper.post("", url);
      logger.info("findByNameOrType  --- " + result);
      status = HttpHelper.isOk;
      if (status) {
       JSONArray array = new JSONArray(result);
       if(array.length() < 1) {
         logger.error("查找不到启用的小组");
         status = false;
         throw new AutoException("查找不到启用的小组 -- 无法添加工作范围，停止");
       }else {
         for(int i=0;i< array.length();i++) {
           JSONObject object = (JSONObject) array.get(i);
           if(object.getString("groupName").equals(groupName)) {
             String groupCode = object.getString("groupCode");
             String groupId = String.valueOf(object.getInt("groupId"));
             groupName = object.getString("groupName");
             
             groupBasicBean = new GroupBasicBean(groupCode,groupId,groupName);
             break;            
           }
         }
       }
      }else {
        throw new AutoException("保存会计任务小组失败");
      }
    }catch(Exception e) {
      throw new AutoException("保存会计任务小组失败");
    }
    
    return groupBasicBean;
    
  }
  
  /**
   * 通过小组id查询组员
   * @param groupId
   */
  public JSONArray findCrewsByGroupId(String groupId) {
    String url = Constants.FIND_CREWS_BY_GROUP_ID_URL +"?groupId" + groupId ;
    try {
      result = HttpHelper.post("", url);
      status = HttpHelper.isOk;
      logger.info("findCrewsByGroupId ---- " + result);
      if(status) {
        try {
          resultJSONArray = new JSONArray(result);
        }catch(JSONException e) {
          logger.error("解析JSON出错");
        }
      }
    }catch(Exception e) {
      throw new AutoException("通过小组id查询组员失败");
    }
   return resultJSONArray;
  }

  public GroupCrewBean findCrewByGroupId(String groupId,String crewName ) {
    GroupCrewBean crewBean = null;
    JSONArray array = findCrewsByGroupId(groupId);
    if(array.length()>0) {
      for(int i=0; i<array.length();i++) {
        JSONObject object = array.getJSONObject(i);
        if(object.getString("crewEmpName").equals(crewName)) {
          String crewEmpName = object.getString("crewEmpName");
          String crewEmpCode = object.getString("crewEmpCode");
          String crewId = String.valueOf(object.get("crewId"));
          String crewEmpId = String.valueOf(object.get("crewEmpId"));
          groupId = String.valueOf(object.get("groupId"));
          crewBean =  new GroupCrewBean(crewEmpName, crewEmpCode, crewId, crewEmpId,
              groupId);
        }
      }
    }
    
    
    return crewBean;
  }
}
